package cn.iocoder.yudao.module.trade.service.ordersafetycheck;

import cn.iocoder.yudao.framework.common.util.CheckUtils;
import cn.iocoder.yudao.framework.common.util.CollectionUtil;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.member.api.user.CrmMemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.CrmMemberUserRespDTO;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.trade.controller.admin.ordersafetycheckitemrelation.vo.OrderSafetyCheckItemRelationRespVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.delivery.DeliveryPickUpStoreDO;
import cn.iocoder.yudao.module.trade.service.delivery.DeliveryPickUpStoreService;
import cn.iocoder.yudao.module.trade.service.ordersafetycheckitemrelation.OrderSafetyCheckItemRelationService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.*;
import cn.iocoder.yudao.module.trade.controller.admin.ordersafetycheck.vo.*;
import cn.iocoder.yudao.module.trade.dal.dataobject.ordersafetycheck.OrderSafetyCheckDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.trade.dal.mysql.ordersafetycheck.OrderSafetyCheckMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.*;

/**
 * 安检单 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class OrderSafetyCheckServiceImpl implements OrderSafetyCheckService {

    @Resource
    private OrderSafetyCheckMapper orderSafetyCheckMapper;

    @Resource
    private OrderSafetyCheckItemRelationService orderSafetyCheckItemRelationService;

    @Resource
    private CrmMemberUserApi crmMemberUserApi;

    @Resource
    private DeptApi deptApi;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private DeliveryPickUpStoreService deliveryPickUpStoreService;

    @Override
    @Transactional
    public Long createOrderSafetyCheck(OrderSafetyCheckSaveReqVO createReqVO) {
        // 插入
        OrderSafetyCheckDO orderSafetyCheck = BeanUtils.toBean(createReqVO, OrderSafetyCheckDO.class);
//        orderSafetyCheck.setCheckName(adminUserApi.getUser(SecurityFrameworkUtils.getLoginUserId()).getUsername());
//        orderSafetyCheck.setNearbyStoresName(orderSafetyCheck.getNearbyStoresId() == null ? null : deptApi.getDept(orderSafetyCheck.getNearbyStoresId()).getName());
        orderSafetyCheck.setCheckStatus(0);
        orderSafetyCheck.setStatus(0);
        orderSafetyCheck.setCreateTime(LocalDateTime.now());
        orderSafetyCheckMapper.insert(orderSafetyCheck);

        if (!CollectionUtil.isEmpty(createReqVO.getRelationRespVOList())) {
            createReqVO.getRelationRespVOList().forEach(x -> {
                x.setCheckId(orderSafetyCheck.getId());
            });
            orderSafetyCheckItemRelationService.saveCheckItemRelationBath(createReqVO.getRelationRespVOList());
        }
        // 返回
        return orderSafetyCheck.getId();
    }

    @Override
    @Transactional
    public void updateOrderSafetyCheck(OrderSafetyCheckSaveReqVO updateReqVO) {
        // 校验存在
        validateOrderSafetyCheckExists(updateReqVO.getId());

        // 审核不通过则需要新增一条安检单
        if (updateReqVO.getCheckStatus() == 2) {

            OrderSafetyCheckRespVO orderSafetyCheck = this.getOrderSafetyCheck(updateReqVO.getId());
            OrderSafetyCheckSaveReqVO orderSafetyCheckSaveReqVO = BeanUtils.toBean(orderSafetyCheck, OrderSafetyCheckSaveReqVO.class);
            orderSafetyCheckSaveReqVO.setId(null);
            orderSafetyCheckSaveReqVO.getRelationRespVOList().forEach(x -> {
                x.setId(null);
            });
            this.createOrderSafetyCheck(orderSafetyCheckSaveReqVO);
        }

        // 更新
        OrderSafetyCheckDO updateObj = BeanUtils.toBean(updateReqVO, OrderSafetyCheckDO.class);
        orderSafetyCheckMapper.updateById(updateObj);
    }

    @Override
    public void deleteOrderSafetyCheck(Long id) {
        // 校验存在
        validateOrderSafetyCheckExists(id);
        // 删除
        orderSafetyCheckMapper.deleteById(id);
    }

    private void validateOrderSafetyCheckExists(Long id) {
        if (orderSafetyCheckMapper.selectById(id) == null) {
            throw exception(ORDER_SAFETY_CHECK_NOT_EXISTS);
        }
    }

    @Override
    public OrderSafetyCheckRespVO getOrderSafetyCheck(Long id) {
        OrderSafetyCheckRespVO respVO = BeanUtils.toBean(orderSafetyCheckMapper.selectById(id), OrderSafetyCheckRespVO.class);
        // 设置燃气户信息
        CrmMemberUserRespDTO crmMember = crmMemberUserApi.getCrmMemberById(respVO.getCrmId());
        respVO.setCrmCode(crmMember.getCode());
        respVO.setCrmMobile(crmMember.getMobile());
        respVO.setCrmType(crmMember.getAccountType());
        respVO.setLicenseNo(crmMember.getLicenseNo());
        DeliveryPickUpStoreDO pickUpStore = deliveryPickUpStoreService.getDeliveryPickUpStore(crmMember.getNearbyStoreId());
        respVO.setCrmStoreName(pickUpStore == null ? "" : pickUpStore.getName());
        respVO.setCrmName(crmMember.getName());
        respVO.setCrmAddress(crmMember.getDetailAddress());

        //查询此燃气户填写安检问卷的 安检项及对应的明细
        List<OrderSafetyCheckItemRelationRespVO> itemRelations = orderSafetyCheckItemRelationService.getCheckItemRelationByCheckId(respVO.getId());
        respVO.setItemRelations(CollectionUtil.isEmpty(itemRelations) ? new ArrayList<>() : itemRelations);
        return respVO;
    }

    @Override
    public PageResult<OrderSafetyCheckRespVO> getOrderSafetyCheckPage(OrderSafetyCheckPageReqVO pageReqVO) {

        List<OrderSafetyCheckRespVO> list = orderSafetyCheckMapper.selectPageList(pageReqVO);
//        Long aLong = orderSafetyCheckMapper.selectPageListByCount(pageReqVO);
        PageResult<OrderSafetyCheckRespVO> result = new PageResult<>(list, (long) list.size());

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderSafetyCheckList(List<OrderSafetyCheckSaveReqVO> updateReqVO) {
        if (CollectionUtil.isEmpty(updateReqVO)){
            return;
        }
        updateReqVO.forEach(x -> {
            if (x.getCheckStatus() == 2) {
                OrderSafetyCheckRespVO orderSafetyCheck = this.getOrderSafetyCheck(x.getId());
                OrderSafetyCheckSaveReqVO orderSafetyCheckSaveReqVO = BeanUtils.toBean(orderSafetyCheck, OrderSafetyCheckSaveReqVO.class);
                orderSafetyCheckSaveReqVO.setId(null);
                orderSafetyCheckSaveReqVO.getRelationRespVOList().forEach(xy -> {
                    xy.setId(null);
                });
                this.createOrderSafetyCheck(orderSafetyCheckSaveReqVO);
            }
            if (x.getCheckStatus() == 1) {
                OrderSafetyCheckDO orderSafetyCheckDO = BeanUtils.toBean(x, OrderSafetyCheckDO.class);
                orderSafetyCheckDO.setUpdateTime(LocalDateTime.now());
                orderSafetyCheckDO.setUpdater(SecurityFrameworkUtils.getLoginUserId().toString());
                orderSafetyCheckMapper.updateById(orderSafetyCheckDO);
            }
        });
//        orderSafetyCheckMapper.updateBatch(BeanUtils.toBean(updateReqVO, OrderSafetyCheckDO.class));
    }

}